import { Form, message } from 'ant-design-vue'
import { pull } from 'lodash-es'
import { type Ref, nextTick, ref } from 'vue'

import { accountApi } from '@/apis'
import type { AccountItem, FormState, Permission } from '@/apis/accountTypes'

type Params = {
  refresh: PromiseFunc

  checkedKeys: Ref<number[]>
  halfCheckedKeys: Ref<number[]>
  allPermissionLength: Ref<Map<number, number>>
  formRules: Ref<FormRules>
}

const { useForm } = Form

export function useEdit({
  refresh,
  checkedKeys,
  halfCheckedKeys,
  allPermissionLength,
  formRules
}: Params) {
  const formState = ref({
    id: 0,
    realName: '',
    userName: '',
    permissions: []
  } as FormState)
  const showEdit = ref(false)

  const formRef = useForm(formState, formRules)

  /** 显示 */
  async function handleShowEdit(item: AccountItem) {
    try {
      const res = await accountApi.getPermission(String(item.id))
      checkedKeys.value = _flattenRoles(res)
      // 移除半选的父节点
      pull(checkedKeys.value, ...halfCheckedKeys.value)
    } finally {
    }
    formState.value.realName = item.realName
    formState.value.userName = item.userName
    formState.value.id = item.id
    showEdit.value = true
  }

  /** 遍历权限 */
  function _flattenRoles(arr: Permission[], result: number[] = []) {
    for (const item of arr) {
      result.push(item.id)

      if (Array.isArray(item.children)) {
        if (item.children.length < allPermissionLength.value.get(item.id)!) {
          halfCheckedKeys.value.push(item.id)
          halfCheckedKeys.value.push(item.parentId)
        }
        _flattenRoles(item.children, result)
      }
    }
    return result
  }

  /** 取消 */
  function handleEditCancel() {
    formRef.resetFields()
    checkedKeys.value = []
  }

  /** 提交 */
  function handleEditAccount() {
    const newCheckedKeys = new Array<number>()
      .concat(checkedKeys.value, halfCheckedKeys.value)
      .map(item => {
        return {
          id: Number(item)
        }
      })
    formState.value.permissions = newCheckedKeys

    nextTick(() => {
      formRef
        .validate()
        .then(async () => {
          await refresh(async () => {
            try {
              await accountApi.editAccount(formState.value)
              message.success('编辑成功')
              showEdit.value = false
              checkedKeys.value = []
              formRef.resetFields()
            } finally {
            }
          })
        })
        .catch((error: any) => {
          console.log('error', error)
        })
    })
  }

  return {
    editFormRef: formRef,
    editFormState: formState,
    showEdit,
    handleShowEdit,
    handleEditAccount,
    handleEditCancel
  }
}
